﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Core.Configuration;
using Inovout.Repositories;
using System.Data;

namespace Inovout.Report
{
    public class DatabaseDataSource : DataSource
    {
        private string databaseName;
        private string queryStatement;
        public DatabaseDataSource(IConfiguration dataSourceConfiguration)
            : base(dataSourceConfiguration)
        {
            foreach (var dstaSourcePropertyConfiguration in dataSourceConfiguration.Children)
            {
                string propertyName = dstaSourcePropertyConfiguration.Attributes["name"];
                switch (propertyName.ToLower())
                {
                    case "databasename":
                        this.databaseName = dstaSourcePropertyConfiguration.Attributes["value"];
                        break;
                    case "querystatement":
                        this.queryStatement = dstaSourcePropertyConfiguration.Attributes["value"];
                        break;
                    default:
                        throw new NotSupportedException(propertyName);
                }
            }
        }

        internal override ReportData[] GetReportData()
        {
            List<ReportData> reportDatas = new List<ReportData>();
            DatabaseRepository databaseRepository = new DatabaseRepository(databaseName);
            reportDatas.AddRange(databaseRepository.GetDatas<ReportData>(queryStatement, FillReportData));
            return reportDatas.ToArray();
        }
        private ReportData FillReportData(IDataReader dataReader)
        {
            ReportData reportData = new ReportData();
            for (int i = 0; i < dataReader.FieldCount; i++)
            {
                reportData.Add(dataReader.GetName(i), dataReader[i] == DBNull.Value ? null : dataReader[i]);
            }
            return reportData;
        }
    }
}
